package com.springx.examples.showcase.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.springx.examples.showcase.common.domain.Message;
import com.springx.examples.showcase.entity.Dictionary;
import com.springx.examples.showcase.repository.mybatis.DictionaryMapper;
import com.springx.examples.showcase.vo.tree.DictionaryVo;
import org.javasimon.aop.Monitored;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Component
@Transactional
@Monitored

public class DictionaryService extends BaseService<Dictionary> {
    @Autowired
    private DictionaryMapper dictionaryMapper;

    /**
     * *
     * 分页查询
     * *
     */
    public Page<DictionaryVo> findPage(Map<String, Object> params, Pageable pageable) {
        PageHelper.startPage((pageable.getPageNumber() - 1) * pageable.getPageSize(), pageable.getPageSize());
        List<DictionaryVo> dictionaryVoList = dictionaryMapper.findList(params);
        PageInfo<DictionaryVo> pageInfo = new PageInfo<>(dictionaryVoList);
        Page<DictionaryVo> page = new PageImpl<DictionaryVo>(pageInfo.getList(), pageable, pageInfo.getTotal());
        return page;
    }

    /**
     * 查找下级
     *
     * @param params
     * @return
     */
    public List<DictionaryVo> findChildren(Map<String, Object> params) {
        return dictionaryMapper.findList(params);
    }

    public String save(Dictionary dictionary) {
        dictionary.setCreateDate(new Date());
        Long pId = (dictionary.getParentId())==null?-1:dictionary.getParentId();
        if (pId == -1) {
            dictionary.setParentId(pId);
            Map<String ,Object> params= Maps.newHashMap();
             params.put("EQ_code", dictionary.getCode());
             List<Dictionary> list =this.selectList(params,null);
            if(list.size()>0){
                return "ERROR";
            }
        }
        else{
            Dictionary dic = this.select(pId);
            dictionary.setCode(dic.getCode() + "_" + dictionary.getCode());
        }
            this.insert(dictionary);//添加排序
            dictionary.setSort(dictionary.getId());
            this.updateByPrimaryKeySelective(dictionary);
        return null;
    }
}
